package com.kaifamiao.ajax;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter( urlPatterns = { "/hello" } )
public class HelloFilter implements Filter {

    @Override
    public void init(FilterConfig config) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) resp ;
        System.out.println( "request method: " + ((HttpServletRequest)req).getMethod() );
        // 设置 响应头中的 Access-Control-Allow-Origin 字段 以便于解决 CORS 问题
        // 这里直接将取值设置为 * 是不合适的，应该根据实际需要指定允许访问的域
        response.setHeader( "Access-Control-Allow-Origin" , "*" );
        // 是否允许后续请求携带认证信息（cookies）,该值只能是true,否则不返回
        response.setHeader( "Access-Control-Allow-Credentials" , "true");
        // 在预检请求的应答中明确了客户端所要访问的资源允许使用的方法或方法列表
        response.setHeader( "Access-Control-Allow-Methods" , "POST, GET, PUT, DELETE, HEAD" );
        System.out.println( resp == response ); // true
        chain.doFilter( req , resp );
    }

    @Override
    public void destroy() {
    }

}
